package com.madou.dbtool.redis.panel.dataloader;

import com.madou.common.annotation.HideClass;
import com.madou.dbtool.common.dto.Complex;
import com.madou.dbtool.language.redis.parser.RedisContentTypeParser;
import com.madou.dbtool.redis.manager.RedisSourceManager;
import com.madou.dbtool.redis.utils.BytesToStringUtil;
import com.madou.dbtool.ui.table.MRow;
import com.madou.dbtool.ui.table.loader.TableDataLoader;
import com.madou.dbtool.ui.table.row.MObjectRow;
import com.madou.dbtool.ui.terminal.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * redis扫描keys
 * @author miukoo
 */
@HideClass
public class RedisScanTableDataLoader implements TableDataLoader {

    private final static String SCAN = "SCAN 0 MATCH *%s* COUNT %d";
    RedisSourceManager redisSourceManager;
    int dbIndex;
    public RedisScanTableDataLoader(RedisSourceManager redisSourceManager,int dbIndex){
        this.redisSourceManager = redisSourceManager;
        this.dbIndex = dbIndex;
    }

    @Override
    public Complex<Integer, List<MRow>> load(Map<String, Object> searchKeyword, int page, int size) {
        String keyword = "";
        if(searchKeyword!=null){
            keyword = (String) searchKeyword.get("keyword");
        }
        if(StringUtils.isEmpty(keyword)){
            keyword = "";
        }
        List<Object> execute = (List<Object>) redisSourceManager.execute(dbIndex,String.format(SCAN,keyword,size));
        List<MRow> collect = new ArrayList<>();
        if(execute!=null&&execute.size()>1){
            List<byte[]> temp = (List<byte[]>) execute.get(1);
            for (int i = 0; i < temp.size(); i++) {
                String field = BytesToStringUtil.byte2Hex(temp.get(i));
                RedisContentTypeParser.redisKeywordTrieLoader.addWord(field);
                collect.add(new MObjectRow(new Complex<Integer,String>(i+1,field)));
            }
        }
        return new Complex<Integer, List<MRow>>(execute.size(),collect);
    }

}
